<?php
namespace WXAPI\Controller;

use Grafika\Grafika;
use Grafika\GrafikaHelper;
use Think\Controller;
use Think\Log;
use Think\Page;

class DriverController extends Controller
{

    public  $store_id='';
    public  $begin='';
    public  $end='';
    public  $driver_id='';

    public function  __construct() {
        parent::__construct();
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: *");
        header('Access-Control-Allow-Methods:*');
        header('Content-Type: application/json; charset=utf-8');
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');

        $methodName = strtolower($_SERVER['REQUEST_METHOD']);

        if ($methodName == "options") {
            exit;
        }
        if(I('driver_mobile')){
            $_GET['mobile'] = I('driver_mobile');
        }

        if(I('mobile')){
            $driver =  M('users')->where(['mobile'=>I('mobile')])->where(" (is_driver=1 or biaoshi = '售后员工') ")->find();


            if($driver){
                $this->driver_id = $driver['user_id'];
            }
        }

        $timegap = I('timegap');

        $timegap = str_replace('+',' ',$timegap);
        //echo $timegap;
        if($timegap){

            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $user_id = $this->driver_id;
            $user = M('users')->where(['user_id'=>$user_id,'is_driver'=>1,'is_lock'=>0])->find(); //查询司机信息
//            if($user && $user['biaoshi_xian']){ //如果是司机就区分快慢线
//                $fast_flag = $user['fast_flag'];
//                if($fast_flag){
//                    $lastweek = date('Y-m-d',strtotime("-1 day")).' 13:00';//上一天一点
//                    $lastweek2 = date('Y-m-d').' 12:00:00';//今天12点
//                }else{
//                    $lastweek = date('Y-m-d',strtotime("-2 day")).' 19:00';//前一天19点
//                    $lastweek2 = date('Y-m-d',strtotime("-1 day")).' 19:00';//上一天19点
//                }
//            }else{
//                $lastweek = date('Y-m-d H:i',strtotime("-2 day"));//2天前
//                $lastweek2 = date('Y-m-d H:i',strtotime("+1 day"));//1天后
//            }
            if($user && $user['biaoshi_xian']){
                $lastweek = date('Y-m-d H:i',strtotime("-2 day"));//2天前
                $lastweek2 = date('Y-m-d H:i',strtotime("+1 day"));//1天后
            }

            if(ACTION_NAME == 'recommend'){
                $lastweek = date('Y-m-d H:i',strtotime("-30 day"));//一个月前
                $lastweek2 = date('Y-m-d H:i',time());//1天后
            }

            $begin = I('begin',$lastweek);
            $end =  I('end',$lastweek2);
        }
        $this->begin = strtotime($begin);
        $this->end = strtotime($end);

    }

    /**
     * 获取配送单列表
     * @return void
     */
    public function getDriverOrderList()
    {
        $p = I('page',0);
        $user_id = $this->driver_id;

        $type = I('type',1);
        $keys = I('keys');
        Log::record(json_encode(I('')),'DEBUG');
        $current_xian = I('current_xian');
        $user = M('users')->where(['user_id'=>$user_id,'is_driver'=>1,'is_lock'=>0])->find(); //查询司机信息
        if($user && $user['biaoshi_xian']){
            $biaoshi_xian = explode(',',$user['biaoshi_xian']);
            if (count($biaoshi_xian) == 1 || !$current_xian){
                $current_xian = $user['biaoshi_xian'];
            }

            $xian_user = M('users')->where(['biaoshi_xian'=>['in',$current_xian]])->order('biaoshi_xian asc')->getField('user_id',true);
            $condition = [];
            //$keys ? $condition['a.order_sn|b.company|b.mobile'] = ['like','%'.$keys.'%'] : false;

            if($keys){
                if(is_numeric($keys)){
                    $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.$keys.',order_sn) > 0');
                    foreach ($subQuery_orderIds as $item){
                        $ids[] = $item['order_id'];
                    }
                    if($ids){
                        $condition['a.order_id'] = ['in',join(',',$ids)];
                    }else{
                        $condition['a.order_id'] = 0;
                    }
                }else{
                    $condition['b.company|b.mobile'] = ['like','%'.$keys.'%'];
                }


            }

            $condition['a.order_status'] = ['lt',3];
            if ($type == 0){ //待出库
                $condition['a.driver_id'] = 0;
                $condition['a.user_id'] = ['in',join(',',$xian_user)];
                $condition['a.driver_time'] = ['exp','IS NULL'];
            }elseif ($type == 1){ //待配送
                $condition['a.driver_id'] = $user_id;
                $condition['a.user_id'] = ['in',join(',',$xian_user)];
                $condition['a.driver_time'] = ['exp','IS NULL'];
            }elseif($type == 2){ //未支付
                $condition['a.pay_status'] = 0;
                $condition['a.driver_id'] = $user_id;
                $condition['a.driver_time'] = ['exp','IS NOT NULL'];

                $condition['a.user_id'] = ['in',join(',',$xian_user)];


            }elseif($type == 3){ //已支付

                $condition['a.pay_status'] = 1;
                $condition['a.driver_id'] = $user_id;

                $condition['a.user_id'] = ['in',join(',',$xian_user)];


            }elseif ($type ==4 ){ //异常
                $this->getReturnOrder($user,$keys,$p,$current_xian);
            }else{
                $condition['a.driver_id'] = $user_id;
                $condition['a.user_id'] = ['in',join(',',$xian_user)];
            }


            if($this->begin && $this->end){
                $condition['a.ruku_last_time'] = array('between',"$this->begin,$this->end");
            }

            $condition['_string'] = 'a.chuku_count > 0  and a.jian_count > 0 and a.chuku_count = a.jian_count and a.shipping_status != 2 ';

            $count = M('order a')
                ->field('a.user_id')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->where($condition)->group('a.user_id')
                ->select();



            $pay_sum = 0;
            if($type == 3){ //选择已支付的时候统计金额
                $pay_list = M('order a')->field('sum(a.order_amount + a.yijia_heji) as order_amount')->where($condition)->find();
                $pay_sum = $pay_list['order_amount'];
            }


            $Page = new Page(count($count), 10);
            $Page->firstRow = $p * $Page->listRows;

            //获取订单列表
            $orderList = M('order a')
                ->field('a.user_id,b.company,b.mobile,a.driver_id,a.driver_time,a.pay_status,b.company_address,sum(a.order_amount + a.yijia_heji) as order_amount,sum(a.jian_count) as jian_count')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->where($condition)
                ->limit("$Page->firstRow,$Page->listRows ")
                ->order('field(a.user_id,'.join(',',$xian_user).')')->group('a.user_id')->select(); //过滤获取主订单


            foreach($orderList as $key=>$v) { //整理子单
                $waitPayPrice = 0;

                $condition['a.user_id'] = $v['user_id'];
                unset($condition['b.company|b.mobile']);
                $order_list = M('order a')
                    ->field('c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
                    ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
                    ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
                    ->where($condition)
                    ->order('a.order_id desc')
                    ->select(); //过滤获取主订单
                //查询产品
                foreach ($order_list as $k=>$v){
                    if($v['pay_status'] == 0){
                        $waitPayPrice+= $v['order_amount'];
                        $orderList[$key]["pay_status"] = 0;
                    }
                    $order_goods = M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.goods_name,((a.member_goods_price + a.yijia) * a.goods_num) as xiaoji,b.original_img,a.goods_num')->where(['order_id'=>$v['order_id']])->select();
                    foreach ($order_goods as $kk=>$vv){
                        $order_goods[$kk]['xiaoji'] = sanwei($vv['xiaoji']);
                        $order_goods[$kk]['goods_num'] = $vv['goods_num'];
                        $order_goods[$kk]['original_img'] = C('MYOSS')['url'].$vv['original_img'];
                    }
                    $order_list[$k]['goods'] = $order_goods;
                }
                $orderList[$key]['wait_pay_price'] = sanwei($waitPayPrice);
                $orderList[$key]["order_list"] = $order_list;
                if(!empty($v['driver_time'])){
                    $orderList[$key]['driver_time'] = date('Y-m-d H:i:s',$v['driver_time']);
                }else{
                    $orderList[$key]['driver_time'] = '未配送';
                }
            }
            exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>$orderList,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end),'pay_sum'=>$pay_sum,'xian'=>explode(',',$user['biaoshi_xian']),'current_xian'=>$current_xian])));

        }else{
            $user = M('users')->where(['user_id'=>$user_id,'biaoshi'=>'售后员工'])->find(); //查询售后员工
            if(!$user){
                exit(json_encode(array("code"=>0,'msg'=>'你不是配送员或售后员工')));
            }
            exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>[],'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));

        }
    }


    /**
     * 订单列表
     * */
    public function getDriverOrderMore(){
        $p = I('page', 0);
        $type = I('type',1);
        $user_id = I('order_user_id');
        $driver_id = $this->driver_id;
        $condition = [];
        $keys = I('keys');
        switch ($type) {
            case 0: //待出库
                $condition['a.driver_time'] = ['exp','IS NULL'];
                $condition['a.driver_id'] = 0;
                break;
            case 1: //待配送
                $condition['a.driver_time'] = ['exp','IS NULL'];
                $condition['a.driver_id'] = $driver_id;
                break;
            case 2: //未支付
                $condition['a.pay_status'] = 0;
                $condition['a.driver_time'] = ['exp','IS NOT NULL'];
                $condition['a.driver_id'] = $driver_id;
                break;
            case 3: //已支付
                $condition['a.pay_status'] = 1;
                $condition['a.driver_id'] = $driver_id;
                break;
            default:
                $condition['a.driver_id'] = $driver_id;
        }
        if($this->begin && $this->end){
            $condition['a.ruku_last_time'] = array('between',"$this->begin,$this->end");
        }


        if($keys){
            if(is_numeric($keys)){
                $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.$keys.',order_sn) > 0');
                foreach ($subQuery_orderIds as $item){
                    $ids[] = $item['order_id'];
                }
                if($ids){
                    $condition['a.order_id'] = ['in',join(',',$ids)];
                }else{
                    $condition['a.order_id'] = 0;
                }
            }
        }

        $condition['a.user_id'] = $user_id;
        $condition['_string'] = 'a.chuku_count > 0  and a.jian_count > 0 and a.chuku_count = a.jian_count and a.shipping_status != 2 ';

        $count = M('order a')
            ->field('c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
            ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
            ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
            ->where($condition)
            ->order('a.order_id desc')
            ->select(); //过滤获取主订单

        $Page = new Page(count($count), 10);
        $Page->firstRow = $p * $Page->listRows;
        $order_list =M('order a')
            ->field('c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
            ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
            ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order('a.order_id desc')
            ->select(); //过滤获取主订单
        foreach ($order_list as $k => $v) {
            $order_goods = M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.goods_name,((a.member_goods_price + a.yijia) * a.goods_num) as xiaoji,b.original_img,a.goods_num,spec_key_name')->where(['order_id' => $v['order_id']])->select();
            foreach ($order_goods as $kk => $vv) {
                $order_goods[$kk]['xiaoji'] = sanwei($vv['xiaoji']);
                $order_goods[$kk]['goods_num'] = $vv['goods_num'];
                $order_goods[$kk]['original_img'] = C('MYOSS')['url'] . $vv['original_img'];
            }
            $order_list[$k]['goods'] = $order_goods;
        }
        exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>$order_list,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));

    }

    /**
     * 获取退货单
     * @return void
     */
    public function getReturnOrder($user,$keys,$p,$current_xian)
    {
        $where='  ';
        if(!empty($keys))
            $where=' and ( c.company like "%'.$keys.'%" or b.store_name like "%'.$keys.'%" or a.order_sn like "%'.$keys.'%" ) ';

        $condition['_string'] = 'a.driver_id ='.$user['user_id'].$where;

        if($this->begin && $this->end){
            $condition['a.addtime'] = array('between',"$this->begin,$this->end");
        }

        $count = M('return_goods a')
            ->join('ty_store b ON a.store_id = b.store_id')
            ->join('ty_users c ON a.user_id = c.user_id')
            ->where($condition)->count();
        $Page = new Page($count, 20);

        $orders = M('return_goods a')->field('a.*,b.store_name,c.company,d.goods_name,e.key_name,d.original_img')
            ->join('ty_store b ON a.store_id = b.store_id')
            ->join('ty_users c ON a.user_id = c.user_id')
            ->join('ty_goods d ON a.goods_id = d.goods_id','LEFT')
            ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
            ->where($condition)->order('a.id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($orders as $k=>$v){
            $orders[$k]['price'] = sanwei(($v['member_goods_price'] + $v['yijia']) * $v['goods_num']);
            $orders[$k]['member_goods_price'] = sanwei(($v['member_goods_price'] + $v['yijia']));
            $orders[$k]['original_img'] = C('MYOSS')['url'].$v['original_img'];
            $orders[$k]['imgs'] = C('MYOSS')['url'].$v['imgs'];
        }


        $return_arr = array('code' => 1, 'msg' => '成功', 'data' => $orders,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end),'xian'=>explode(',',$user['biaoshi_xian']),'current_xian'=>$current_xian]);
        exit(json_encode($return_arr));
    }


    /**
     * 司机操作配送单
     * @return void
     */
    public function setOrderDriver()
    {
        $order_id = I('order_id');
        $user_id = $this->driver_id;
        $user = M('users')->where(['user_id'=>$user_id])->find();
        if($user && $user['is_driver']){
            if($order_id){
                $master_order_sn = get_order_sn();
                M('pay_merge_log')->add(['master_order_sn'=>$master_order_sn,'order_sn'=>$order_id,'add_time'=>date('Y-m-d H:i:s',time())]); //记录合并订单
                $order = M('order')->where('order_id in ('.$order_id.') and driver_time IS NULL')->select();
                foreach ($order as $item){
                    M('order')->where(['order_id'=>$item['order_id']])->save(['driver_id'=>$user_id,'driver_time'=>time()]);
                }
                M('order')->where('order_id in ('.$order_id.')')->save(['pay_master_order_sn'=>$master_order_sn]);
                if(C('pay_online') == 0){
                    $driver_biaoshi_xian = $user['biaoshi_xian'];
                    $driver_biaoshi_xian = explode(',',$driver_biaoshi_xian);
                    if(count($driver_biaoshi_xian) > 1){
                        $user_id = M('order')->where('order_id in ('.$order_id.')')->getField('user_id');
                        $user['biaoshi_xian'] = M('users')->where(['user_id'=>$user_id])->getField('biaoshi_xian');
                    }
                    $pay_code = M('line')->where(['title'=>$user['biaoshi_xian']])->getField('images');
                    $pay_code = SITE_URL.$pay_code;
                }
//                $pay = new PayController();
//                $payUrl = $pay->payApp($master_order_sn);


                $return_arr = array('code' => 1, 'msg' => '操作成功', 'data' => ['pay_url'=>$pay_code,'company'=>'','trxamt'=>0,'old_trxamt'=>0,'pay_online'=>C('pay_online'),'return_price'=>0,'pay_status'=>0,'user_money'=>0]);
                exit(json_encode($return_arr));
            }

        }else{
            exit(json_encode(array("code"=>0,'msg'=>'你不是配送员', 'data' => [])));
        }
    }


    /**
     * 司机登录
     * @return void
     */
    public function driverLogin(){
        $username = I('mobile');


        $user = M('users')->where("mobile='{$username}' and (is_driver=1 or biaoshi = '售后员工') ")->find();
        if(!$user){
            $result = array('code'=>0,'msg'=>'账号不存在!','data'=>[]);
        }elseif($user['is_lock'] == 1){
            $result = array('code'=>0,'msg'=>'账号异常已被锁定！！！','data'=>[]);
        }else{
            //查询用户信息之后, 查询用户的登记昵称
            $user['token'] = md5(time().mt_rand(1,999999999));
            $user['type'] = 4;
            M('users')->where("user_id = {$user['user_id']}")->save(array('token'=>$user['token'],'last_login'=>time()));
            $result = array('code'=>1,'msg'=>'登陆成功','data'=>$user);
        }


        if($result['code'] != 1)
            exit(json_encode($result));


        exit(json_encode($result));

    }


    /**
     * 司机操作退货获取订单产品
     * @return void
     */
    public function getOrderGoods()
    {
        $order_id=I('order_id',0);
        $list=M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.*,b.original_img')->where('order_id='.$order_id)->select();
        foreach ($list as $k=>$v){
            $list[$k]['goods_num'] = round($v['goods_num']);
            $list[$k]['original_img'] = C('MYOSS')['url'].$v['original_img'];
            $list[$k]['member_goods_price'] = sanwei($v['member_goods_price']+$v['yijia']);
            $return_num = M('return_goods')->where(['order_id'=>$order_id,'goods_id'=>$v['goods_id'],'spec_key'=>$v['spec_key']])->sum('goods_num');
            $list[$k]['return_max'] = $list[$k]['goods_num']-$return_num;
        }
        $return_arr = array('code' => 1, 'msg' => '成功', 'data' => $list);
        exit(json_encode($return_arr));
    }

    /**
     * 司机操作退货
     * @return void
     */
    public function saveReturnOrder()
    {
        try {
            M()->startTrans();
            $result = file_get_contents("php://input");
            $result = json_decode($result,true);
            $goodGoods=json_decode($result['goodGoods'],true);

            $return_remark=$result['return_remark'];
            $imageUrl=$result['imageUrl'];
//            $isReturnNow = $result['isReturnNow'];//是否理解退款
            $returnType = $result['returnType'];//退货类型
            if(!$return_remark){
                $return_arr = array('code' => 0, 'msg' => '请选择理由', 'data' => []);
                exit(json_encode($return_arr));
            }
            if($goodGoods){
                $order_sn = get_order_sn();
                foreach($goodGoods as $key=>$v){
                    $order_goods = M('order_goods')->where(['rec_id'=>$v['rec_id']])->find();
                    $return_num = M('return_goods')->where(['order_id'=>$v['order_id'],'status'=>['neq',3],'goods_id'=>$v['goods_id'],'spec_key'=>$v['spec_key']])->sum('goods_num');
                    if($v['goods_num'] > round($order_goods['goods_num'])-round($return_num)){
                        // if($v['goods_num'] > $order_goods['goods_num']-$return_num){
                        $return_arr = array('code' => 0, 'msg' => '添加失败,退货数超出订单数量', 'data' => []);
                        exit(json_encode($return_arr));
                    }
                    if($v['goods_num'] > $order_goods['goods_num']){
                        $v['goods_num'] = $order_goods['goods_num'];
                    }
                    if($v['goods_num'] > 0){
                        $store = M('store')->where(['store_id'=>$v['store_id']])->find();
                        if($store && $store['open_return'] == 0){
                            $return_arr = array('code' => 0, 'msg' => '该店铺已经关闭售后', 'data' => []);
                            exit(json_encode($return_arr));
                        }
                        $order = M('order o')
                            ->field('o.*,u.fenbu_id as fenbu_id')
                            ->join('ty_users u on u.user_id = o.user_id','LEFT')
                            ->where(['o.order_id'=>$v['order_id']])
                            ->find();
                        if($order && $order['coupon_price'] > 0){
                            $return_arr = array('code' => 0, 'msg' => '添加失败,订单使用了优惠券不能退货', 'data' => []);
                            exit(json_encode($return_arr));
                        }

                        if($order['fenbu_id'] == 0 || $order['fenbu_id'] == 42){
                            $getorder = 0;
                            $rukuTime = time();
                        }else{
                            $getorder = 2;
                            $rukuTime = '';
                        }

                        $a = M('return_goods')->add([
                            'order_sn'=>$order['order_sn'],
                            'return_order_sn'=>$order_sn,
                            'order_id'=>$v['order_id'],
                            'fenbu_id'=>$order['fenbu_id'],
                            'ufenbu_id'=>$order['ufenbu_id'],
                            'goods_id'=>$v['goods_id'],
                            'user_id'=>$order['user_id'],
                            'store_id'=>$v['store_id'],
                            'goods_num'=>$v['goods_num'],
                            'remark'=>$return_remark,
                            'addtime'=>time(),
                            'tuihuo_time'=>time(),
                            'member_goods_price'=>$v['member_goods_price'] - $v['yijia'],
                            'points'=>$v['points'],
                            'reason'=>'',
                            'spec_key'=>$v['spec_key'],
                            'yijia'=>$v['yijia'],
                            'driver_id'=>$order['driver_id'],
                            'getorder'=>$getorder,
                            'is_app'=>1,
                            'ruku_time'=>$rukuTime,
                            'type'=>$returnType,
                            'imgs'=>$imageUrl??'',
                            //'is_online'=>$order['pay_no'] != '' && $order['pay_status'] == 1 ? 1 : 0
                        ]);

//                        if($isReturnNow && $order['pay_no'] != '' && $order['pay_status'] == 1){ //立即退款
//                            $returnOrder = M('return_goods')->where(['id'=>$a])->find();
//                            $payModel = new PayController();
//                            $payModel->returnOrder($returnOrder);
//                        }
                    }
//                    else{
//                        $return_arr = array('code' => 0, 'msg' => '请填下数量', 'data' => []);
//                        exit(json_encode($return_arr));
//                    }
                    //$tui_jifen+=($v['member_goods_price'] + $v['yijia'])*$v['goods_num'];

                }

                M()->commit();

                update_user_level($order['user_id']);
                //开始退积分
                //accountLog($order['user_id'],0,-$tui_jifen,'订单 '.$order['order_sn'].' 退货扣的积分！',0,$order['order_id']);
                $return_arr = array('code' => 1, 'msg' => '操作成功', 'data' => $a);
                exit(json_encode($return_arr));
            }else{
                $return_arr = array('code' => 0, 'msg' => '添加失败,数据为空', 'data' => []);
                exit(json_encode($return_arr));
            }
        }catch (\Exception $e){
            M()->rollback();
            Log::record($e->getMessage(),'ERR');
            $return_arr = array('code' => 0, 'msg' => '添加失败', 'data' => []);
            exit(json_encode($return_arr));
        }

    }


    /*
   * 获取我的下级
   * */
    public function recommend(){
        $user_id = $this->driver_id;
        $p = I('page',0);
        $name = I('name');
        $type = I('type',0);
        $user = M('users')->where(['user_id'=>$user_id])->find(); //查询司机信息
        if(!empty($user)){
            if($user['is_driver'] != 1 ){
                exit(json_encode(array("code"=>-1,'msg'=>'你不是配送员')));
            }else{
                $condition = [];
                $condition['parent_id'] = $user_id;

                if($name){
                    $condition['company'] = ['like',"%$name%"];
                }
                if($this->begin && $this->end){
                    $condition['reg_time'] = array('between',"$this->begin,$this->end");
                }
                if($type == 1){
                    $condition['_string'] = "(last_sale  between $this->begin AND $this->end) AND last_sale IS NOT NULL";
                }
                if($type == 2){
                    $condition['_string'] = "(last_sale not between $this->begin AND $this->end) OR last_sale IS NULL";
                }


                $count = M('users')
                    ->where($condition)
                    ->select();

                $Page = new Page(count($count), 20);
                $Page->firstRow = $p * $Page->listRows;
                $userlist = M('users')
                    ->where($condition)
                    ->limit("$Page->firstRow,$Page->listRows ")
                    ->select();

                foreach ($userlist as &$item){
                    $item['reg_time'] = date('Y-m-d H:i:s',$item['reg_time']);
                }
                exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>$userlist,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));
            }

        }else{
            exit(json_encode(array("code"=>'-1','msg'=>'获取失败')));
        }
    }

    /*
     *通过审核
     * */
    public function apiexamine(){
        $user_id = I('client_id');
        $is_lock = I('is_lock');
        $user = M('users')->where(['user_id'=>$user_id])->find(); //查询司机信息

        if(!empty($user)){
            if($is_lock == 1){
                $is_lock = 0;
            }else{
                $is_lock = 1;
            }
            M('users')->where(['user_id'=>$user_id])->fetchSql(true)->save(['is_lock'=>$is_lock]);

            exit(json_encode(array("code"=>1,'msg'=>'修改成功','data'=>[])));
        }else{
            exit(json_encode(array("code"=>'-1','msg'=>'获取失败')));
        }
    }


    /**
     * 司机推广码
     * @return void
     * @throws \Exception
     */
    public function driverRecommendation(){
        $GoodsModel = new GoodsController();
        $user_id = $this->driver_id;
        $userInfo = M('users')->where(['user_id'=>$user_id])->find();
        $goods_pic_url = $userInfo["recommendImg"];
        $goods_pic_url=SITE_URL.$goods_pic_url;

        $goods_pic_save_path =QRCODE_PATH.'/users';
        $goods_pic_save_name = md5($user_id). '.jpg';
        $pic_url=SITE_URL."/Public/goodsqrcode/users".$goods_pic_save_name;
        if (file_exists($goods_pic_save_path . $goods_pic_save_name)) {


            $result = array('code'=>1,'msg'=>'获取成功','data'=>[
                'user_id' => $user_id,
                'status' =>1,
                'pic_url' => $pic_url . '?v=' . time(),
            ]);
            $json_str = json_encode($result,true);
            exit($json_str);
        }
        $goods_pic_path = $GoodsModel->saveTempImage($goods_pic_url);
        if (!$goods_pic_path){
            $json_arr = array('code'=>0,'msg'=>'获取商品海报失败：商品图片丢失');
            $json_str = json_encode($json_arr,true);
            exit($json_str);
        }

        //获取小程序码图片
        $wxapp_qrcode_file_res = $GoodsModel->getQrcode('', $user_id,'user');
        $wxapp_qrcode_file_path = $wxapp_qrcode_file_res['file_path'];
        if($userInfo['recommendImg'] != $pic_url){
            M('users')->where(['user_id'=>$user_id])->save(['recommendImg'=>$pic_url]);
        }
        //保存图片
        $editor = Grafika::createEditor(GrafikaHelper::getSupportEditorLib());

        $editor->open($wxapp_qrcode, $wxapp_qrcode_file_path);
        $editor->save($wxapp_qrcode, $goods_pic_save_path . $goods_pic_save_name, 'jpeg', 85);
        unlink($goods_pic_path);
        unlink($wxapp_qrcode_file_path);
        $json_arr = array('code'=>1,'msg'=>'获取成功','data'=>[
            'user_id' => $user_id,
            'pic_url' => $pic_url . '?v=' . time(),
        ] );
        $json_str = json_encode($json_arr,true);
        exit($json_str);

    }


    public function chuku()
    {
        $user_id = $this->driver_id;
        $order_id = I('order_id');
        $chuku_num=I("chuku_num");
        $pda_name_chuku=I("pda_name_chuku");
        $ruku_num=I("ruku_num");
        $pda_name_ruku=I("pda_name_ruku");

        $pda_pd2=M('pda')->where('pda_name="'.$pda_name_chuku.'"')->find();
        if(!$pda_pd2){
            exit(json_encode(array("code"=>0,'msg'=>'未认证设备')));
        }

        if($ruku_num && $pda_name_ruku){
            $chuku_num = $ruku_num;
            $pda_name_chuku = $pda_name_ruku;
        }
        $basic=tpCache("basic");
        $user = M('users')->where(['user_id'=>$user_id])->find(); //查询司机信息
        if(!empty($user)){

            $order = M('order a')->field('a.ufenbu_id,b.biaoshi_xian,a.chuku_last_time')->join('ty_users b ON a.user_id = b.user_id')->where(['a.order_id'=>$order_id])->find();
            $biaoshi_xian = explode(',',$user['biaoshi_xian']);
            if($order && ($order['ufenbu_id'] == $user['fenbu_id'] && in_array($order['biaoshi_xian'],$biaoshi_xian))){

                //判断总部和分部字段
//                $z=!empty($pda_pd) ? 'z' : '';
                $z='';

                $orders=M('order_jian a')
                    ->field('a.*,b.order_sn,b.consignee,b.jian_count,b.user_id')
                    ->join('ty_order b on a.order_id=b.order_id')
                    ->where('a.order_id='.$order_id.' and a.'.$z.'status_c=0 and a.'.$z.'chuku_num='.$chuku_num)->find();

                if($orders){
                    //判断是否出库
                    $pd=M('order_jian')
                        ->where('order_id='.$order_id.' and '.$z.'status_r=0')->find();
                    if($pd){
                        exit(json_encode(array("code"=>0,'msg'=>'此单未入库，禁止出库！')));
                    }
                    $pds=M('order')->where('order_id='.$order_id.' and order_status in (3,5)')->find();
                    if($pds){
                        exit(json_encode(array("code"=>0,'msg'=>'此单已取消！')));
                    }

                    $timestamp = strtotime('today '.$basic['not_ruku_time']);
                    if($pds['add_time'] > $timestamp){
                        echo I('callback')."(".json_encode([
                                'code'=>'50',
                                'infos'=>'此单明天扫码，禁止扫码！'
                            ]).")";
                        exit;
                    }


                    $chuku_time = strtotime(date("Y-m-d H:i:s"));
                    $orderInfo = M('order')->where('order_id='.$order_id)->find();
                    if($orderInfo['ruku_count'] != $orderInfo['chuku_count']){
                        M('order')->where('order_id='.$order_id)->setInc('chuku_count');
                        if(!$order['chuku_last_time']){
                            M('order')->where('order_id='.$order_id)
                                ->save([
                                    'chuku_last_time'=>$chuku_time,
                                    'driver_id'=>$user_id,
                                    'pda_qdzt'=>0,
                                ]);
                        }
                    }

                    $orderData = M('order')->where('order_id='.$order_id)->find();
                    if($orderData['chuku_count'] > $orderData['ruku_count']){
                        M('order')->where('order_id='.$order_id)->setField(['chuku_count'=>$orderData['ruku_count']]);
                    }



                    M('order_jian')
                        ->where('order_id='.$order_id.' and '.$z.'status_c=0 and '.$z.'chuku_num='.$chuku_num)
                        ->save([
                            $z.'pda_name_chuku'=>$pda_name_chuku,
                            $z.'chuku_time'=>$chuku_time,
                            $z.'status_c'=>'1'
                        ]);

                    exit(json_encode(array("code"=>1,'msg'=>'出库成功','data'=>true)));
                }else{
                    exit(json_encode(array("code"=>0,'msg'=>'此单已经出库！','data'=>true)));
                }

            }else{
                exit(json_encode(array("code"=>0,'msg'=>'你与标签上的线路、区域不匹配')));
            }

        }else{
            exit(json_encode(array("code"=>0,'msg'=>'获取失败')));
        }
    }


    /**
     * 扫码退货入库
     * @return void
     */
    public function rukuReturn()
    {
        $id = I('id');
        $user_id = $this->driver_id;
        $reutrn = M('return_goods')->where(['id'=>['in',$id]])->find();
        $order = M('order')->where(['order_id'=>$reutrn['order_id']])->find();
        $user = M('users')->where(['user_id'=>$user_id,'is_lock'=>0])->find();

        if($order['ufenbu_id'] == 0 ){
            exit(json_encode(array("code"=>0,'msg'=>'不是分部退货单')));
        }

        if($user['biaoshi'] != '售后员工'){
            exit(json_encode(array("code"=>0,'msg'=>'你不是售后员工,无法入库退货商品')));
        }
        if($reutrn['getorder'] == 0){
            exit(json_encode(array("code"=>0,'msg'=>'此单已入库')));
        }

        M('return_goods')->where(['id'=>['in',$id]])->save(['getorder'=>0,'ruku_time'=>time()]);
        exit(json_encode(array("code"=>'1','msg'=>'入库成功')));


    }
     /**
     * 司机操作维修
     * @return void
     */
    public function saveFixOrder()
    {
        try {
            M()->startTrans();
            $result = file_get_contents("php://input");
            Log::record($result);
            $result = json_decode($result,true);
            $goodGoods=json_decode($result['goodGoods'],true);

            $driver_mobile=$result['driver_mobile'];
            $return_remark=$result['return_remark'];
            $imageUrl=$result['imageUrl'];
            $driver =  M('users')->where(['mobile'=>$driver_mobile])->where(" (is_driver=1 or biaoshi = '售后员工') ")->find();

            if(!$return_remark){
                $return_arr = array('code' => 0, 'msg' => '请选择理由', 'data' => []);
                exit(json_encode($return_arr));
            }
            if($goodGoods){

                foreach($goodGoods as $key=>$v){
                    $order_goods = M('order_goods')->where(['rec_id'=>$v['rec_id']])->find();
                    $return_num = M('fix_goods')->where(['order_id'=>$v['order_id'],'goods_id'=>$v['goods_id'],'spec_key'=>$v['spec_key']])->sum('goods_num');
                    if($v['goods_num'] > round($order_goods['goods_num'])-round($return_num)){
                        $return_arr = array('code' => 0, 'msg' => '添加失败,维修货数超出订单数量', 'data' => []);
                        exit(json_encode($return_arr));
                    }
                    if($v['goods_num'] > $order_goods['goods_num']){
                        $v['goods_num'] = $order_goods['goods_num'];
                    }
                    if($v['goods_num'] > 0){

                        $order = M('order o')
                            ->field('o.*,u.fenbu_id as fenbu_id')
                            ->join('ty_users u on u.user_id = o.user_id','LEFT')
                            ->where(['o.order_id'=>$v['order_id']])
                            ->find();


                        $a = M('fix_goods')->add([
                            'order_sn'=>$order['order_sn'],
                            'order_id'=>$v['order_id'],
                            'goods_id'=>$v['goods_id'],
                            'user_id'=>$order['user_id'],
                            'store_id'=>$v['store_id'],
                            'type'=>1,
                            'goods_num'=>$v['goods_num'],
                            'remark'=>$return_remark,
                            'fix_time'=>time(),
                            'addtime'=>time(),
                            'member_goods_price'=>$v['member_goods_price'],
                            'reason'=>'',
                            'spec_key'=>$v['spec_key'],
                            'driver_id'=>$driver && $driver['user_id'] ? $driver['user_id'] : $order['driver_id'],
                            'is_app'=>1,
                            'imgs'=>$imageUrl??'',
                            //'jian_count'=>$v['jian_count']
                        ]);

//                        if($v['jian_count'] > 0){
//                            changeReturnJianCount('fix_goods',$a,$v['jian_count']);
//                            M('fix_goods')->where(['id'=>$a])->save(['ruku_count'=>0,'chuku_count'=>0,'ruku_time'=>'']);
//                        }
                    }
                }

                M()->commit();

                $return_arr = array('code' => 1, 'msg' => '操作成功', 'data' => $a);
                exit(json_encode($return_arr));
            }else{
                $return_arr = array('code' => 0, 'msg' => '添加失败,数据为空', 'data' => []);
                exit(json_encode($return_arr));
            }
        }catch (\Exception $e){
            M()->rollback();
            Log::record($e->getMessage(),'ERR');
            $return_arr = array('code' => 0, 'msg' => '添加失败', 'data' => []);
            exit(json_encode($return_arr));
        }

    }

    /**
     * 查询退款状态
     */
//    public function check_return_play(){
//        $id=I('id');
//        if(!empty($id)){
//            $returnOrder = M('return_goods')->where(['id'=>$id])->find();
//            $payModel = new PayController();
//            $result = $payModel->check_return_play($returnOrder);
//            exit(json_encode($result));
//        }
//
//    }

}